package com.itheima.controller;


import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.pojo.Order;
import com.itheima.service.AddressService;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    //远程调用
    @Reference
    private AddressService addressService;

  @Reference
  private OrderService orderService;
    //本地注入 Jedis 方法
    @Autowired
   private JedisPool jedisPool;



    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //获取手机号
        String telephone = (String)map.get("telephone");
        //利用手机号获取缓存中的验证码
        //String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
       //获取前端页发来的验证码
        String validateCode = (String)map.get("validateCode");
        //比对验证码是否相同
      // if (validateCode != null && validateCodeInRedis!=null && validateCode.equals(validateCodeInRedis)){
           if (validateCode != null){
               //验证通过 调用下层方法完成 预约
           map.put("orderType", Order.ORDERTYPE_WEIXIN);
           Result result= null;
           try {
               result = orderService.order(map);
           } catch (Exception e) {
               e.printStackTrace();
               //如果报错 为预约失败
               return result;
           }
           if(result.isFlag()){
               //预约成功了
          /*     try {
                   //预约成功了 给手机号发送预约成功短信
                   SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String)map.get("orderDate"));
               } catch (ClientException e) {
                   e.printStackTrace();
               }*/
           }
           return result;
           }else{
               //验证失败,返回消息
               return new Result(false,MessageConstant.VALIDATECODE_ERROR);
           }
    }

    //按id查询信息
  @RequestMapping("/findById")
    public Result findById (Integer id){
      try {
          Map map=orderService.findById(id);
          return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
      } catch (Exception e) {
          e.printStackTrace();
          return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
      }
  }

  @RequestMapping("/findAll")
    public Result findAll(){
        List<Address> list = addressService.findAll();
        return new Result(true,"查询地址成功",list);
  }

}
